//
//  ContactsUtil.m
//  kabao51
//
//  Created by Dream on 2018/4/28.
//  Copyright © 2018年 Dream. All rights reserved.
//

#import "ContactsUtil.h"
#import <Contacts/Contacts.h>
#import <ContactsUI/ContactsUI.h>

@interface ContactsUtil ()<CNContactPickerDelegate>

/** block */
@property (nonatomic, copy) ContactCompletionBlock completionBlock;

@end

@implementation ContactsUtil

/** 创建单例 */
+ (ContactsUtil *)sharedUtil
{
    static ContactsUtil *sharedUtil = nil;
    
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        
        sharedUtil = [[self alloc] init];
    });
    return sharedUtil;
}

#pragma mark - all contacts phones

+ (void)getUserAllContacts:(void (^)(NSArray *contacts, NSError *error))completionHandler
{
    //准许获取通讯录
    CNContactStore *contactStore = [[CNContactStore alloc] init];
    
    CNAuthorizationStatus authorizationStatus = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    
    //不确定授权或者拒绝授权
    if (authorizationStatus == CNAuthorizationStatusNotDetermined || authorizationStatus == CNAuthorizationStatusDenied) {
        
        //授权
        [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
            
            if (granted == YES) {
                //通过授权
                completionHandler([ContactsUtil getContacts], nil);
            }
            else {
                //拒绝授权
                NSError *error = [NSError errorWithDomain:@"通讯录授权被用户拒绝" code:10001 userInfo:nil];
                
                completionHandler(@[], error);
            }
        }];
    }
    //已经授权
    else if (authorizationStatus == CNAuthorizationStatusAuthorized) {
        
        completionHandler([ContactsUtil getContacts], nil);
    }
    //账户限制（父母的控制）
    else {
        
        NSError *error = [NSError errorWithDomain:@"账户通讯录权限被限制" code:10002 userInfo:nil];
        
        completionHandler(@[], error);
    }
}

/** 通讯录所有信息 */
+ (NSArray *)getContacts
{
    NSMutableArray *contacts = [[NSMutableArray alloc] init];
    
    //获取指定的字段，并不是要获取所有字段，需要指定具体的字段
    NSArray *keysToFetch = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey];
    
    CNContactFetchRequest *fetchRequest = [[CNContactFetchRequest alloc] initWithKeysToFetch:keysToFetch];
    
    CNContactStore *contactStore = [[CNContactStore alloc] init];
    
    [contactStore enumerateContactsWithFetchRequest:fetchRequest error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
        
        //特殊字符
        NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@／：；（）¥「」＂、[]{}#%-*+=_\\|~＜＞$€^•'@#$%^&*()_+'\" "];
        
        //全名 = familyName + givenName
        NSString *nameStr = [[NSString stringWithFormat:@"%@%@",contact.familyName,contact.givenName] stringByTrimmingCharactersInSet:set];
        
        //手机号码
        NSArray *phoneNumbers = contact.phoneNumbers;
        
        NSMutableString *phoneMutableStr = [NSMutableString string];
        
        for (int i = 0; i < phoneNumbers.count; i++) {
            
            CNLabeledValue *labelValue = phoneNumbers[i];
            
            NSNumber *phoneNumber = labelValue.value;
            
            //去除手机号码特殊字符
            NSString *tempStr = [phoneNumber.stringValue stringByReplacingOccurrencesOfString:@"-" withString:@""];
            
            NSString *phoneStr = [tempStr stringByReplacingOccurrencesOfString:@"·" withString:@""];
            
            if (phoneNumbers.count == 1) {
                
                [phoneMutableStr appendString:phoneStr];
            }
            else {
                
                if (i != phoneNumbers.count - 1) {
                    
                    [phoneMutableStr appendFormat:@"%@,", phoneStr];
                }
                else {
                    
                    [phoneMutableStr appendFormat:@"%@", phoneStr];
                }
            }
        }
        
        NSString *phoneStr = [[[phoneMutableStr stringByTrimmingCharactersInSet:set] componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""];
        
        //去除+86
        if ([phoneStr hasPrefix:@"+86"]) {
            
            NSMutableCharacterSet *set = [NSMutableCharacterSet new];
            [set addCharactersInString:@"+86"];
            
            phoneStr = [phoneStr stringByTrimmingCharactersInSet:set];
        }
        
        
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
        
        dictionary[@"name"] = (nameStr.length) > 0 ? nameStr : @"未知";
        
        dictionary[@"mobile"] = phoneStr;
        
        [contacts addObject:dictionary];
    }];
    
    return contacts;
}

#pragma mark - single phone
/** 单个用户的手机号 */
- (void)getSingleUserPhoneWithVC:(UIViewController *)vc completion:(ContactCompletionBlock)completion
{
    CNContactPickerViewController *contactPickerViewController = [[CNContactPickerViewController alloc] init];
    
    contactPickerViewController.delegate = self;
    
    [vc presentViewController:contactPickerViewController animated:YES completion:nil];
    
    self.completionBlock = completion;
}

- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker
{
    NSLog(@"取消");
}

//选择通讯录个人 获取所有信息
//- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact
//{
//
//}

//选择通讯录个人 获取指定信息
// 注意:如果实现该方法，上面那个方法就不能实现了，这两个方法只能实现一个
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContactProperty:(CNContactProperty *)contactProperty
{
    CNPhoneNumber *phoneNumber = contactProperty.value;
    
    //非手机号
    if (![contactProperty.value isKindOfClass:[CNPhoneNumber class]]) {
        
        if (self.completionBlock) {
            
            NSError *error = [NSError errorWithDomain:@"非手机号" code:10003 userInfo:nil];
            
            self.completionBlock(@"", error);
        }
        return;
    }
    
    //空号
    if (phoneNumber.stringValue.length == 0) {
        
        if (self.completionBlock) {
            
            NSError *error = [NSError errorWithDomain:@"空号" code:10004 userInfo:nil];
            
            self.completionBlock(@"", error);
        }
        return;
    }
    
    NSString *tempStr = [phoneNumber.stringValue stringByReplacingOccurrencesOfString:@"-" withString:@""];
    
    NSString *phoneStr = [[tempStr componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""];
    
    //去除+86
    if ([phoneStr hasPrefix:@"+86"]) {
        
        NSMutableCharacterSet *set = [NSMutableCharacterSet new];
        [set addCharactersInString:@"+86"];
        
        phoneStr = [phoneStr stringByTrimmingCharactersInSet:set];
    }
    
    if (self.completionBlock) {
        
        self.completionBlock(phoneStr, nil);
    }
}

@end
